﻿CREATE PROCEDURE [dbo].[usp_insert_Message]
(
	 @MessageID			uniqueidentifier
	,@FaultID			uniqueidentifier
	,@NativeMessageID	varchar(256)
	,@ContentType		varchar(128)
	,@MessageName		varchar(50)
	,@InterchangeID		varchar(256)
	,@RoutingUrl		varchar(50)
	,@MessageData		varchar(max)    	
	,@Debug				bit = 1
)
AS

/****************************************************************************
Name: usp_insert_Message.sql
Description:  Inserts a message into the Message table.
*****************************************************************************/
SET NOCOUNT ON;

-- Bootstrap
DECLARE @DebugPrefix       varchar(10);
DECLARE @ErrorCode         int;

SET @ErrorCode          = 0;
SET @DebugPrefix        = '>>> DEBUG: ';


-- Test harness
/*
DECLARE @Debug           bit;
DECLARE @NativeMessageID varchar(128)
DECLARE	@MessageID		 uniqueidentifier
DECLARE @FaultID		 uniqueidentifier
DECLARE	@ContentType	 varchar(128)
DECLARE @MessageName	 varchar(50)
DECLARE @InterchangeID	 varchar(50)
DECLARE @RoutingUrl		 varchar(50)
DECLARE @MessageData	 varbinary(max)
DECLARE @InsertedDate	 datetime
DECLARE @InsertedBy		 varchar(50)
DECLARE @ModifiedDate	 datetime
DECLARE @ModifiedBy		 varchar(50)

SELECT
	 @MessageID			= NEWID()		
	,@FaultID			= NEWID()	
	,@ContentType	
	,@MessageName
	,@InterchangeID	
	,@RoutingUrl	
	,@MessageData	
	,@InsertedDate	
	,@InsertedBy	
	,@ModifiedDate	
	,@ModifiedBy
	,@Debug                 = 1;

*/

-- Print parameters
/*IF (@Debug > 0)
BEGIN
    PRINT @DebugPrefix + '@MessageID = ' + CAST(@MessageID AS varchar(38));
    PRINT @DebugPrefix + '@FaultID = ' + CAST(@FaultID AS varchar(38));
	PRINT @DebugPrefix + '@ContentType = ' + CAST(@ContentType AS varchar(500));
	PRINT @DebugPrefix + '@MessageName = ' + CAST(@MessageName AS varchar(500));
	PRINT @DebugPrefix + '@InterchangeID = ' + CAST(@InterchangeID AS varchar(38));
END;*/

		-- FIX: Content Type
		IF (@ContentType = 'text/plain' AND LEFT(@MessageData,1) = '<')
		BEGIN
		  SET @ContentType = 'text/xml'
		END

		--Insert the error report
		INSERT INTO dbo.Message(
				MessageID
			   ,FaultID
			   ,NativeMessageID
			   ,ContentType
			   ,MessageName
			   ,InterchangeID
			   ,RoutingUrl
		 ) VALUES (
           		 @MessageID		
				,@FaultID
				,@NativeMessageID
				,@ContentType		
				,@MessageName
				,@InterchangeID	
				,@RoutingUrl	
		)

		--Insert the MessageData
		INSERT INTO dbo.MessageData(
			MessageID,
			MessageData
		)
		VALUES (
			 @MessageID
			,@MessageData
		)	
			
RETURN 0;

-- Handles errors.
ERROR_HANDLER:
IF (@ErrorCode <> 0)
BEGIN
    IF (@Debug > 0) 
		BEGIN
			PRINT @DebugPrefix + 'Error Code = ' + CAST(@ErrorCode AS varchar(10)) + ' occurred.';
			RETURN @ErrorCode
		END

    -- Don't return any evidence of what specific error occurred, i.e. 
    -- we want to ward off potential hackers.
    RETURN 1;
END;

SET NOCOUNT OFF;
